﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MINERP.MODEL.EM;
using MINERP.BLL.EM;
using MINERP.COM;
using System.Runtime.InteropServices;


namespace MINERP.ComControls
{
    public delegate List<UsersInfo> GetSendListHandler();

    public partial class frmMain : FrmParent
    {
        private bool _isFlickerMsgTip = true;
        private bool _isFlickerText = true;
        private string tempText = "";
        private Image _picMsgTip;
        private int _userid;
        private bool _isShowMenuForm = false;
        private static frmMain _instance = null;
        private frmChat frmchat = null;
        //public static delegate void SetTreeUserBoxesEventHandler(bool bl);
        //public static event SetTreeUserBoxesEventHandler SetTreeUserBoxesChange;
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        /// <summary>
        /// 临时存储消息队列
        /// </summary>
        private List<MessagesInfo> _MsgList;

        public frmMain()
        {
           
            InitializeComponent();
            base.InitiAuthority();
            _picMsgTip = btnToolMessage.Image; //
            AppSetter.AllHeaders = imgAllHeaders;

        }
        private frmMain(int userId)
        {
            //SetTreeUserBoxesChange += new SetTreeUserBoxesEventHandler(SetTreeUserCheckBoxes);

            _userid = userId;
            InitializeComponent();
            _picMsgTip = btnToolMessage.Image; //
            AppSetter.AllHeaders = imgAllHeaders;
            this.Disposed +=new EventHandler(frmMain_Disposed);
            //  _FlickerFaces = imgAllHeaders;
        }

        public static frmMain GetInstance(int userid)
        {
            if (_instance == null)
            {
                _instance = new frmMain(userid);
            }
            return _instance;
        }

        //protected override void OnClosed(EventArgs e)
        //{
        //    Application.Exit();
        //}

        /// <summary>
        /// 显示我的好友列表信息
        /// </summary>
        private void BindMyFriends()
        {
            //sbFriends.Groups[0].Items.Clear();
            //List<FriendsInfo> _FList = Friends.GetFriends(AppSetter.CurrentUser.Id);
            //foreach (FriendsInfo obj in _FList)
            //{
            //    SbItem item = new SbItem(obj.Friend.NickName, obj.Friend.FaceId);
            //    item.ContextMenuStrip = cmsPopu;
            //    item.Tag = obj.Friend;

            //    sbFriends.Groups[0].Items.Add(item);
            //}
        }

        /// <summary>
        /// 刷新显示我的个人信息
        /// </summary>
        private void RefreshMyInfo()
        {
            AppSetter.CurrentUser = Users.Select(_userid);
            this.Text = AppSetter.CurrentUser.NickName.ToString();
            lblMyTitle.Text = AppSetter.CurrentUser.NickName + "(" + AppSetter.CurrentUser.Id.ToString() + ")";
            //picMyHeader.Image = AppSetter.AllHeaders.Images[AppSetter.CurrentUser.FaceId];
        }

        private void frmMain_Load(object sender, EventArgs e)
        {

            if (_userid<=0)
            {
                _isShowMenuForm = base.isShowMenuForm;
                _userid = base.userId;
            }      
            RefreshMyInfo();
            //sbFriends.AddGroup("我的好友");
            //sbFriends.AddGroup("陌生人");
            //sbFriends.Groups[0].Tag = "0";
            //sbFriends.Groups[1].Tag = "1";
            //BindMyFriends();
            LinkTreeFriends();
            timer1.Enabled = true;


        }

        private void LoadMessages()
        {

        }

        /// <summary>
        /// 头像闪烁
        /// </summary>
        private void HeaderFlicker(int groupIndex, int headerIndex)
        {

            // if(string.IsNullOrEmpty(sbFriends.Groups[groupIndex].Items[headerIndex].Text))
            //    tempText = sbFriends.Groups[groupIndex].Items[headerIndex].Text;

            //if (_isFlickerText)
            // {
            //     sbFriends.Groups[groupIndex].Items[headerIndex].Text = "";
            //     _isFlickerText = false;
            // }
            // else
            // {
            //     sbFriends.Groups[groupIndex].Items[headerIndex].Text = tempText;
            //     _isFlickerText = true;
            // }

        }
        /// <summary>
        /// 获取当前用户未读信息
        /// </summary>
        public void GetMessages()
        {
            try
            {
                _MsgList = Messages.GetMyNotReadMessages(AppSetter.CurrentUser.Id);
                if (_MsgList.Count > 0)
                {
                    FlickerMessageTip();
                    ShowChatFormWhenGetMessage();
                    //HeaderFlicker(0,2);  
                }
                else if (btnToolMessage.Image == null)
                {
                    btnToolMessage.Image = _picMsgTip;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 闪烁消息提示
        /// </summary>
        private void FlickerMessageTip()
        {
            if (_isFlickerMsgTip)
            {
                btnToolMessage.Image = _picMsgTip;
                _isFlickerMsgTip = false;
            }
            else
            {
                btnToolMessage.Image = null;
                _isFlickerMsgTip = true;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //GetMessages();
            SetOffLineState();
        }

        private void btnToolMessage_Click(object sender, EventArgs e)
        {
            if (_MsgList.Count > 0)
            {
                MessagesInfo objMsg = _MsgList[0];
                int iMsgType = objMsg.MessageType.Id;
                if (iMsgType == (int)EnumMessageType.ChatMessage)
                {
                    List<UsersInfo> list = new List<UsersInfo>();
                    list.Add(objMsg.FromUser);
                    frmChat frmchat = new frmChat();
                    frmchat.SetTreeUser += new EventHandler(SetTreeUserCheckBoxes);
                    frmchat.FriendList = list;
                    frmchat.ReceiveMessage = objMsg;
                    frmchat.Show();
                }

            }
        }

        private void btnToolRefresh_Click(object sender, EventArgs e)
        {
            BindMyFriends();
        }

        private void cmsSmallHeader_Click(object sender, EventArgs e)
        {
            //if (sbFriends.View != SbView.SmallIcon)
            //{
            //    sbFriends.View = SbView.SmallIcon;
            //    cmsSmallHeader.Text = "大头像";
            //}
            //else
            //{
            //    sbFriends.View = SbView.LargeIcon;
            //    cmsSmallHeader.Text = "小头像";

            //}
        }



        private void cmsDeleteFriend_Click(object sender, EventArgs e)
        {

            //if (sbFriends.SeletedItem != null)
            //{

            //    //从陌生人里删除
            //    if (sbFriends.SeletedItem.Parent.Tag.ToString() == "1")
            //    {
            //        sbFriends.Groups[0].Items.Remove(sbFriends.SeletedItem);
            //    }
            //    else
            //    {
            //        //从服务器里删除
            //        UsersInfo tempUser = ((UsersInfo)sbFriends.SeletedItem.Tag);
            //        if (DialogResult.Yes == MessageBox.Show("您真的要删除[" + tempUser.NickName + "]好友吗？", "提示", MessageBoxButtons.YesNo))
            //        {
            //            Friends.DeleteFriend(AppSetter.CurrentUser.Id, tempUser.Id);
            //            BindMyFriends();
            //            MoveToStrangeList(tempUser);
            //        }

            //    }
            //}


        }

        private void btntoolSendMessagetoAll_Click(object sender, EventArgs e)
        {
            treeView1.CheckBoxes = true ;
            frmChat frm = new frmChat();
            frm.SetTreeUser += new EventHandler(SetTreeUserCheckBoxes);
            frm.getSendList += new GetSendListHandler(GetFriendList);
            frm.Show();
        }

        private List<UsersInfo> GetFriendList()
        {
            List<UsersInfo> userList = new List<UsersInfo>();
            for (int i = 0; i < treeView1.Nodes.Count; i++)
            {
                if (treeView1.Nodes[i].Nodes.Count > 0)
                {
                    foreach (TreeNode item in treeView1.Nodes[i].Nodes)
                    {
                        if (item.Tag != null&&item.Checked ==true)
                        {
                            userList.Add(Users.Select((int)item.Tag));
                        }
                    }
                }
                
            }
            return userList;
        }

        private void LinkTreeFriends()
        {
            List<DepartmentInfo> deplist = DepartMentBLL.SelectAll();
            List<UsersInfo> userList = Users.SelectAll();

            //TreeNode [] userNodeArry = null;
            foreach (var dep in deplist)
            {
                List<TreeNode> userNodeList = new List<TreeNode>();
                foreach (var user in userList)
                {
                    if (user.DepName == dep.DepName)
                    {
                        TreeNode node = new TreeNode(user.NickName);
                        node.Tag = user.Id;

                        if (IsOnLine(user.Id))
                        {
                            node.ImageIndex = imageList1.Images.IndexOfKey("head.gif");
                            node.SelectedImageIndex = imageList1.Images.IndexOfKey("head.gif");
                        }
                        else
                        {
                            node.ImageIndex = imageList1.Images.IndexOfKey("offline.gif");
                            node.SelectedImageIndex = imageList1.Images.IndexOfKey("offline.gif");
                        }
                        Image am=imageList1.Images[0];
                       
                        userNodeList.Add(node);

                    }

                }

                TreeNode depNode = new TreeNode(dep.DepName, userNodeList.ToArray());
                depNode.ImageIndex = imageList1.Images.IndexOfKey("right.gif");
                depNode.SelectedImageIndex = imageList1.Images.IndexOfKey("down.GIF");
                this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
             depNode});
            }


        }

        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            foreach (TreeNode node in e.Node.Nodes)
                node.Checked = e.Node.Checked;
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (!e.Node.IsExpanded && e.Node.Nodes.Count != 0 && !e.Node.TreeView.CheckBoxes)
            {
                e.Node.TreeView.CollapseAll();
                e.Node.Expand();
            }
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag != null)
            {
                UsersInfo userInfo = Users.Select((int)e.Node.Tag);
                List<UsersInfo> list = new List<UsersInfo>();
                frmChat frmchat = new frmChat();
                frmchat.SetTreeUser += new EventHandler(SetTreeUserCheckBoxes);
                frmchat.FriendList = list;
                frmchat.FriendList.Add(userInfo);
                frmchat.CurrentFriend = userInfo;

                frmchat.Show();
            }
        }
        private void SetTreeUserCheckBoxes(object sender, EventArgs e)
        {
            treeView1.CheckBoxes = false;
        }

        private void btnToolHeaderConfig_Click(object sender, EventArgs e)
        {

        }

        public override void FrmParent_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_isShowMenuForm)
            {
                Logoff.ShowMainFrm();
            }
        }
        private void ShowChatFormWhenGetMessage()
        {
            MessagesInfo objMsg = _MsgList[0];
            int iMsgType = objMsg.MessageType.Id;
            if (iMsgType == (int)EnumMessageType.ChatMessage)
            {
                List<UsersInfo> list = new List<UsersInfo>();
                list.Add(objMsg.FromUser);
                if ((int)FindWindow(null, "与" + objMsg.FromUser.NickName + "对话中") <= 0)
                {
                    frmchat = new frmChat();
                    frmchat.SetTreeUser += new EventHandler(SetTreeUserCheckBoxes);
                }
                else
                {
                    frmchat = ((MINERP.ComControls.frmChat)(Control.FromHandle(FindWindow(null, "与" + objMsg.FromUser.NickName + "对话中"))));
                }

                frmchat.FriendList = list;
                frmchat.ReceiveMessage = objMsg;
                frmchat.TopMost = true;
                frmchat.WindowState = FormWindowState.Normal;
                frmchat.Show();
            }
        }


        private void SetOffLineState()
        {
            List<TreeNode> listNode = new List<TreeNode>();
            foreach (TreeNode item in treeView1.Nodes)
	        {
                foreach (TreeNode node in item.Nodes)
                {
                    if (IsOnLine((int)node.Tag))
                    {
                        node.ImageIndex = imageList1.Images.IndexOfKey("head.gif");
                    }
                    else
                    {
                        node.ImageIndex = imageList1.Images.IndexOfKey("offline.gif");
                    }
                }
	        }
            //treeView1.Refresh();

        }

        /// <summary>
        /// 操作员是否在线
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        private bool IsOnLine(int userid)
        {
            return Users.Select(userid).IsOnline;
        }
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            _instance = null;

        }
        private void frmMain_Disposed(object sender, EventArgs e)
        {
            _instance = null;
        }
    }
}